# -*- coding: utf-8 -*-
import sys
import os
import json
from flask import Flask, request, jsonify, Response
from datetime import datetime
import redis
from notifier import EmailNotifier

# --- 系统初始化 ---

# 设置UTF-8编码
if hasattr(sys.stdout, 'reconfigure'):
    sys.stdout.reconfigure(encoding='utf-8')
if hasattr(sys.stderr, 'reconfigure'):
    sys.stderr.reconfigure(encoding='utf-8')

os.environ.setdefault('PYTHONIOENCODING', 'utf-8')

app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False

# --- 全局组件 ---

# Redis 连接
try:
    redis_client = redis.Redis(
        host=os.getenv('REDIS_HOST', 'localhost'),
        port=int(os.getenv('REDIS_PORT', 6379)),
        decode_responses=True
    )
    redis_client.ping()
    print("✅ Redis 连接成功")
except redis.exceptions.ConnectionError as e:
    print(f"❌ Redis 连接失败: {e}")
    redis_client = None

# 邮件告警通知器
notifier = None

# --- 辅助函数 ---

def json_response(data, status_code=200):
    """返回支持中文的JSON响应"""
    json_str = json.dumps(data, ensure_ascii=False, indent=2)
    return Response(json_str, status=status_code, mimetype='application/json; charset=utf-8')

def init_notifier():
    """初始化邮件告警通知器"""
    global notifier
    try:
        notifier = EmailNotifier()
        print("✅ 邮件告警通知器初始化成功")
    except Exception as e:
        print(f"❌ 邮件告警通知器初始化失败: {e}")
        print("💡 提示: 请检查SMTP相关环境变量配置")
        notifier = None

# --- API 路由 ---

@app.route('/', methods=['GET'])
def index():
    """根路径接口，显示服务状态"""
    smtp_config_status = {
        "host": os.getenv('SMTP_HOST', '未配置'),
        "port": os.getenv('SMTP_PORT', '未配置'),
        "user": os.getenv('SMTP_USER', '未配置'),
        "sender": os.getenv('SMTP_SENDER_EMAIL', '未配置'),
        "default_recipient": os.getenv('DEFAULT_RECIPIENT_EMAIL', '未配置')
    }
    return json_response({
        "service": "DeepGuard 告警服务",
        "version": "3.0.0 (Email Edition)",
        "status": "running",
        "timestamp": datetime.now().isoformat(),
        "notification_method": "SMTP Email",
        "notifier_status": "已初始化" if notifier else "未初始化",
        "redis_status": "已连接" if redis_client else "未连接",
        "smtp_config": smtp_config_status,
        "endpoints": {
            "健康检查": "/health",
            "发送告警": "/send-alarm (POST)",
            "告警历史": "/alarm-history"
        }
    })

@app.route('/health', methods=['GET'])
def health_check():
    """健康检查接口"""
    return json_response({
        "status": "healthy",
        "service": "alarm-service",
        "timestamp": datetime.now().isoformat(),
        "email_notifier": "ready" if notifier else "not_ready",
        "redis_connection": "ready" if redis_client else "not_ready"
    })

@app.route('/send-alarm', methods=['POST'])
def send_alarm():
    """接收告警并通过邮件发送通知"""
    if not notifier:
        return json_response({
            "success": False,
            "error": "邮件通知器未初始化",
            "hint": "请检查SMTP环境变量配置并重启服务"
        }, 503)

    try:
        data = request.get_json()
        
        # 验证必要字段
        required_fields = ['level', 'type', 'details']
        if not all(field in data for field in required_fields):
            return json_response({"success": False, "error": "缺少必要字段: level, type, details"}, 400)
        
        # 获取收件人邮箱
        recipient_email = data.get('email', os.getenv('DEFAULT_RECIPIENT_EMAIL'))
        if not recipient_email:
            return json_response({
                "success": False,
                "error": "未指定收件人邮箱",
                "hint": "请在请求中提供 email 或在环境变量中设置 DEFAULT_RECIPIENT_EMAIL"
            }, 400)
        
        # 构建邮件内容
        level = data['level']
        alarm_type = data['type']
        details = data['details']
        
        subject = f"【{level}级告警】DeepGuard 安全告警: {alarm_type}"
        
        body = f"""
您好,

DeepGuard 安全监控系统检测到一则新的安全告警，详情如下：

- 告警类型: {alarm_type}
- 危险级别: {level}
- 发生时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
- 详细信息: {details}

请您尽快登录系统进行核查与处理。

---
此邮件由 DeepGuard 系统自动发送，请勿回复。
"""
        
        # 发送邮件
        success, message = notifier.send_email(recipient_email, subject, body)
        
        # 记录告警历史到Redis
        if redis_client:
            alarm_record = {
                "timestamp": datetime.now().isoformat(),
                "level": level,
                "type": alarm_type,
                "details": details,
                "recipient_email": recipient_email,
                "send_success": success,
                "send_result": message
            }
            redis_client.lpush("alarm_history", json.dumps(alarm_record, ensure_ascii=False))
            redis_client.ltrim("alarm_history", 0, 999)

        if success:
            return json_response({"success": True, "message": "告警邮件发送成功"})
        else:
            return json_response({"success": False, "error": "发送告警邮件失败", "details": message}, 500)
            
    except Exception as e:
        return json_response({"success": False, "error": str(e)}, 500)

@app.route('/alarm-history', methods=['GET'])
def get_alarm_history():
    """获取告警历史记录"""
    if not redis_client:
        return json_response({"success": False, "error": "Redis未连接，无法获取历史记录"}, 503)
        
    try:
        limit = int(request.args.get('limit', 20))
        history = redis_client.lrange("alarm_history", 0, limit - 1)
        records = [json.loads(record) for record in history]
        return json_response({"success": True, "data": records, "total": len(records)})
    except Exception as e:
        return json_response({"success": False, "error": str(e)}, 500)

# --- 服务启动 ---

if __name__ == '__main__':
    print("🚀 启动 DeepGuard 告警服务 (SMTP邮件模式)...")
    
    # 显示环境变量状态
    print("\n--- SMTP 配置 ---")
    print(f"SMTP_HOST: {os.getenv('SMTP_HOST', '未设置')}")
    print(f"SMTP_PORT: {os.getenv('SMTP_PORT', '未设置')}")
    print(f"SMTP_USER: {os.getenv('SMTP_USER', '未设置')}")
    print(f"SMTP_PASSWORD: {'已设置' if os.getenv('SMTP_PASSWORD') else '未设置'}")
    print(f"SMTP_SENDER_EMAIL: {os.getenv('SMTP_SENDER_EMAIL', '未设置')}")
    print(f"DEFAULT_RECIPIENT_EMAIL: {os.getenv('DEFAULT_RECIPIENT_EMAIL', '未设置')}")
    print("-------------------\n")

    print("正在初始化邮件告警通知器...")
    init_notifier()
    
    port = int(os.getenv('INTERNAL_CALLBACK_PORT', 23847))
    print(f"\n✅ 服务已启动，监听端口: http://0.0.0.0:{port}")
    app.run(host='0.0.0.0', port=port, debug=False)